import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import sys
import json
import zipfile
import tempfile
from pathlib import Path

# 添加核心模块路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(current_dir, 'core'))
sys.path.insert(0, os.path.join(current_dir, 'ui'))

try:
    from core.loader import MCUILoader
    from core.resource_manager import ResourceManager
    from core.animation_engine import AnimationEngine
    from core.renderer import MCUIRenderer
    from ui.styles import setup_minecraft_theme
    print("所有模块导入成功")
except ImportError as e:
    print(f"导入错误: {e}")
    print("请确保所有核心模块都存在")

class MCUIViewer:
    def __init__(self, file_path=None):
        self.root = tk.Tk()
        self.root.title("MCUI Viewer V1.1.0")
        self.root.geometry("1000x800")
        
        # 初始化资源管理器和动画引擎
        self.resource_manager = ResourceManager()
        self.animation_engine = AnimationEngine()
        self.loader = MCUILoader()  # 初始化加载器
        
        # 设置主题
        try:
            setup_minecraft_theme(self.root)
        except Exception as e:
            print(f"主题设置失败: {e}")
        
        # 当前加载的MCUI数据
        self.mcui_data = None
        self.current_page_index = 0
        
        self.setup_ui()
        
        # 如果有命令行参数，直接打开文件
        if file_path and os.path.exists(file_path):
            self.open_file_path(file_path)
        
        # 绑定窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        
    def on_closing(self):
        """窗口关闭时的清理工作"""
        # 清理资源
        self.animation_engine.cleanup()
        self.resource_manager.cleanup()
        self.loader.cleanup()
        
        # 关闭窗口
        self.root.destroy()
        
    def setup_ui(self):
        """设置主界面"""
        # 主框架
        self.main_frame = ttk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 内容区域
        self.content_frame = ttk.Frame(self.main_frame)
        self.content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 导航区域
        self.nav_frame = ttk.Frame(self.main_frame)
        self.nav_frame.pack(fill=tk.X, pady=5)
        
        self.prev_btn = ttk.Button(self.nav_frame, text="上一页", command=self.prev_page)
        self.prev_btn.pack(side=tk.LEFT)
        
        self.page_label = ttk.Label(self.nav_frame, text="页面: 0/0")
        self.page_label.pack(side=tk.LEFT, padx=10)
        
        self.next_btn = ttk.Button(self.nav_frame, text="下一页", command=self.next_page)
        self.next_btn.pack(side=tk.LEFT)
        
        # 菜单
        menubar = tk.Menu(self.root)
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(label="打开MCUI文件", command=self.open_file_dialog)
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.on_closing)
        menubar.add_cascade(label="文件", menu=file_menu)
        
        self.root.config(menu=menubar)
        
    def open_file_dialog(self):
        """通过对话框打开MCUI文件"""
        file_path = filedialog.askopenfilename(
            title="选择MCUI文件",
            filetypes=[("MCUI文件", "*.mcui"), ("所有文件", "*.*")]
        )
        
        if file_path:
            self.open_file_path(file_path)
    
    def open_file_path(self, file_path):
        """打开指定路径的MCUI文件"""
        try:
            # 清理之前的资源
            self.animation_engine.cleanup()
            self.resource_manager.cleanup()
            self.loader.cleanup()
            
            # 加载新文件
            self.mcui_data = self.loader.load(file_path)
            self.current_page_index = 0
            
            # 设置资源根目录
            assets_root = self.mcui_data.get('_assets_root', os.path.dirname(file_path))
            self.resource_manager.set_assets_root(assets_root)
            
            # 更新窗口标题显示文件名
            file_name = os.path.basename(file_path)
            self.root.title(f"MCUI Viewer - {file_name}")
            
            self.render_current_page()
        except Exception as e:
            messagebox.showerror("错误", f"加载文件失败: {str(e)}")
            import traceback
            traceback.print_exc()
    
    def render_current_page(self):
        """渲染当前页面"""
        # 清除当前内容
        for widget in self.content_frame.winfo_children():
            widget.destroy()
            
        if not self.mcui_data or 'pages' not in self.mcui_data:
            return
            
        pages = self.mcui_data['pages']
        if self.current_page_index >= len(pages):
            return
            
        current_page = pages[self.current_page_index]
        
        # 更新导航状态
        self.page_label.config(text=f"页面: {self.current_page_index + 1}/{len(pages)}")
        self.prev_btn.config(state=tk.NORMAL if self.current_page_index > 0 else tk.DISABLED)
        self.next_btn.config(state=tk.NORMAL if self.current_page_index < len(pages) - 1 else tk.DISABLED)
        
        # 渲染页面
        try:
            renderer = MCUIRenderer(self.content_frame, self.resource_manager, self.animation_engine)
            renderer.render_page(current_page, self.mcui_data)
        except Exception as e:
            messagebox.showerror("渲染错误", f"渲染页面失败: {str(e)}")
            import traceback
            traceback.print_exc()
    
    def prev_page(self):
        """上一页"""
        if self.current_page_index > 0:
            self.current_page_index -= 1
            self.render_current_page()
    
    def next_page(self):
        """下一页"""
        if self.mcui_data and self.current_page_index < len(self.mcui_data['pages']) - 1:
            self.current_page_index += 1
            self.render_current_page()
    
    def run(self):
        """运行应用"""
        self.root.mainloop()

if __name__ == "__main__":
    # 检查命令行参数
    if len(sys.argv) >= 2:
        file_path = sys.argv[1]
        print(f"从命令行打开文件: {file_path}")
        app = MCUIViewer(file_path)
    else:
        app = MCUIViewer()
    
    app.run()